﻿define("vm.aupair.view",
	["jquery", "ko", "common", "vm.aupair.favorite", "ajax-util", "dataservice", "model.aupair.photos", "presenter"],
	function ($, ko, common, favAp, util, ds, apPhotosObj, presenter) {
		var aupairInformation = ko.observableArray(),
			headingNotes = ko.observableArray(),
			aupairPhotos = ko.observableArray(),
			contactInformationView = ko.observableArray(),
			myFamilyView = ko.observableArray(),
			myLifestyleView = ko.observableArray(),
			myHealthView = ko.observableArray(),
			myPreferencesView = ko.observableArray(),
			childcareExperienceView = ko.observableArray(),
			referencesView = ko.observableArray(),
			workExperienceView = ko.observableArray(),
			evaluationView = ko.observableArray(),
			apProfileAndEEView = ko.observableArray(),
			adminView = ko.observableArray(),
			drivingSwimmingView = ko.observableArray(),
			interestsView = ko.observableArray(),
			educationView = ko.observableArray(),
			extensionView = ko.observableArray(),
			extPrgPhotos = ko.observableArray(),
			apStatus = ko.observable(),
			canReserve = ko.observable(),
			canFavorite = ko.observable(),
			isPrint = ko.observable(),
			extensionTabVisible = ko.observable(),
			showInformation = ko.observable(0),
			apLetter = ko.observableArray(),
			scrollPage = false,
			scrollToID = '',
			comparisonMatches = ko.observableArray(),
			isCurrentAP = ko.observable(),
			apCountryCultureInfo = ko.observable(),
			showExtentionInfo = ko.observable(),
			primaryMatches = ko.observableArray(),
			selectedAupairForExtendedHold = ko.observable(),
			apExtensionInfo = ko.observable(),
			hfpmname = ko.observable(),
			personType = ko.observable(),
			HasValidHFKey = ko.observable(),
			appcode = ko.observable(),

		ageGroups = [
			'0 to 1 year old',
			'1 to 2 years old',
			'2 to 3 years old',
			'3 to 5 years old',
			'5 to 8 years old',
			'8 years or older'
		],

		moreChildExpAgeGroups = [
			'0 to 1 year old',
			'1 to 2 years old',
			'2 to 3 years old',
			'4 years or older'
		],

		timesOfDaycare = ['Daytime', 'Evening', 'Overnight'],
		
		SetAppCode = function (code) {
			appcode(code);
		},

		init = function (pLoadPhotos) {
			if (appcode() == 'SAS') { // SAS
				isPrint(false);
				$.when(GetContactInformation(pLoadPhotos)).then(function () {
					if (extensionTabVisible()) {
						GetExtension();
					}
					else {
						GetLetter();
					}
					CanReserveAndFavoriteAupair();
					GetMyPreferences();
				});
				
				GetHFPMInfo();
			}
			else { //SAV
				isPrint(false);
				$('.add-as-fav').click(
					function () {
						MakeFavoriteAndOpenCommentWindow();
					});
				$("#divBlockedReserve").hide();
				$('.add-as-fav').magnificPopup({
					items: {
						type: 'inline',
						src: '#favCom'
					}
				});

				$('.remove-from-recommend-aupair').magnificPopup({
					items: {
						type: 'inline',
						src: '#divRemoveRecommendAupair'
					}
				});

				$('#aLCCReleaseAupair').magnificPopup({
					items: {
						type: 'inline',
						src: '#divLCCReleaseAupair'
					}
				});

				$('.aAProfileAndEE').magnificPopup({
					items: {
						type: 'inline',
						src: '#divAProfileAndEE'
					}
				});

				favAp.GetStaffDuties();
				GetLetter();
				GetContactInformation(pLoadPhotos);
				GetMyPreferences();
				CanReserveAndFavoriteAupair();			
			}
		},

		SetPersonType = function (val) {
		    personType(val);
		    var mhf = common.GetQueryStringValue('MHF');
		    if (mhf == null || mhf == undefined || mhf == '') {
		        HasValidHFKey(false);
		    }
		    else {
		        HasValidHFKey(true);
		    }
		},

		GetHFPMInfo = function () {
			ds.hostfamily.GetPMInfo({
				success: function (data) {
					if (data != undefined && data != null) {
						$.each(data, function (key, val) {
							hfpmname(val);
						});
					}
				},
				error: function (response) {
				}
			});
		},

		 MakeAupairFavorite = function (d, obj) {
			 if (canFavorite() != 0) {
				 favAp.MakeFavorite(common.GetAupairID(), $(obj.target));
			 }
			 else {
				 selectedFavAPDataToRemove = this;
				 common.ShowMessage('', 'remove-from-fav');
			 }
		 },

		AnimatePage = function () {
			var element;
			element = $('.p-container');
			presenter.AnimateElement(element);
		},

		GetLockedClass = function (pShowInfo) {
			if (!pShowInfo)
				return "locked";
			else
				return "";
		},

		CanReserveAndFavoriteAupair = function (pVal) {
			ds.aupair.CanReserveAndFavoriteAupair({
				success: function (pResult) {
					canFavorite(pResult[0].CanFavoriteAP);
					canReserve(pResult[0].IsAPReservable);
					isCurrentAP(pResult[0].IsCurrentAP);
					if (pResult[0].IsAPReservable == "matched-with-you") {
						showInformation(1);
					}
					else {
						showInformation(0);
					}
					getPrimaryMatchesofFamily();
				},
				error: function () {
					common.ErrorNotify(msgs["viewer_load_options_error"])
				}
			}, common.GetAupairID(pVal));
		},

		detectHeight = function () {
			$('.aside-infos .bq-container blockquote p').each(function () {
				var $this = $(this),
					nbLinesToDisplay = ($(window).width() > 768) ? 3 : 2,
					divheight = parseInt($this.css('height'), 10),
					lineheight = parseInt($this.css('line-height'), 10),
					nbLines = Math.round(divheight / lineheight),
					closedHeight = (lineheight * nbLinesToDisplay) + 20;
				if (nbLines > nbLinesToDisplay) {
					$this.css('height', closedHeight);
					$this.closest('.bq-container').addClass('overflown');
				} else {
					$this.parent('.bq-container').removeClass('overflown');
					$this.css('height', '100%');
				}
			});
		},

		GetContactInformation = function (pLoadPhotos) {
		    greyedBackground.show();
			return $.Deferred(function (def) {
				var AupairID = common.GetAupairID();
				ds.aupairView.GetContactInformation({
					success: function (pResult) {
						aupairInformation(pResult.personalInformation);
						aupairInformation().EncAupairID = AupairID;
						if (IsPrimaryMatch()) {
							GetComparisonMatches();
						}
						greyedBackground.hide();
						$('.app-actions').css('visibility', 'visible');
						contactInformationView(pResult);
						apStatus(pResult.personalInformation.APStatus);
						headingNotes(pResult.headingNotes);
						detectHeight();
						extensionTabVisible(common.IsExtensionAP(aupairInformation().Status));
						tooltips['lock'] = tooltips['lock'].replace('<<firstname>>', pResult.personalInformation.FirstName);
						tooltips['lock-extension'] = tooltips['lock-extension'].replace('<<firstname>>', pResult.personalInformation.FirstName);
						if (pLoadPhotos) {
							aupairPhotos.removeAll();
							$.each(pResult.aupairPhotos, function (key, val) {
								aupairPhotos.push(new apPhotosObj(val));
							});
							InvokeSlider();
							setTimeout(function () {
								CaptionOverflow();
								$(window).resize(CaptionOverflow);
							}, 500);
						}
						def.resolve();
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["viewer_load_contact_error"]);
						def.reject();
					}
				}, AupairID);
			}).promise();
		},

		GetMyFamily = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetMyFamily({
				success: function (pResult) {
					greyedBackground.hide();
					myFamilyView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_family_error"])
				}
			}, AupairID);
		},

		GetMyLifestyle = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetMyLifestyle({
				success: function (pResult) {
					greyedBackground.hide();
					myLifestyleView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_lifestyle_error"])
				}
			}, AupairID);
		},

		GetMyHealth = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetMyHealth({
				success: function (pResult) {
					greyedBackground.hide();
					myHealthView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_health_error"])
				}
			}, AupairID);
		},

		GetChildcareExperience = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetChildcareExperience({
				success: function (pResult) {
					greyedBackground.hide();
					childcareExperienceView(pResult);
					if (scrollPage) {
						if (scrollToID !== undefined)
							$('html,body').animate({ scrollTop: $('#' + scrollToID).offset().top }, 'slow');
						scrollPage = false;
						scrollToID = '';
					}
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_childcare_error"])
				}
			}, AupairID);
		},

		GetReferences = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetReferences({
				success: function (pResult) {
					greyedBackground.hide();
					referencesView(pResult);

					if (scrollPage) {
						if (scrollToID !== undefined)
							$('html,body').animate({ scrollTop: $('#' + scrollToID).offset().top }, 'slow');
						scrollPage = false;
						scrollToID = '';
					}
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_references_error"])
				}
			}, AupairID);
		},

		GetWorkExperience = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetWorkExperience({
				success: function (pResult) {
					greyedBackground.hide();
					workExperienceView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_experience_error"])
				}
			}, AupairID);
		},

		GetEvaluation = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetEvaluation({
				success: function (pResult) {
					greyedBackground.hide();
					evaluationView(pResult);
					if (pResult.approfileandee != undefined && pResult.approfileandee.length > 0) {
						apProfileAndEEView(pResult.approfileandee);

						$('.aAProfileAndEE').magnificPopup({
							items: {
								type: 'inline',
								src: '#divAProfileAndEE'
							}
						});
					}
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_evaluation_error"])
				}
			}, AupairID);
		},

		GetDrivingSwimming = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetDrivingSwimming({
				success: function (pResult) {
					greyedBackground.hide();
					drivingSwimmingView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_swimming_error"])
				}
			}, AupairID);
		},

		GetInterests = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetInterests({
				success: function (pResult) {
					greyedBackground.hide();
					interestsView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_interests_error"])
				}
			}, AupairID);
		},

		GetEducation = function () {
			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetEducation({
				success: function (pResult) {
					greyedBackground.hide();
					educationView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_education_error"])
				}
			}, AupairID);
		},

		GetExtension = function () {
			greyedBackground.show();
			ds.aupairView.GetExtension({
				success: function (pResult) {
					greyedBackground.hide();
					showExtentionInfo(pResult.ShowExtentionInfo)
					extensionView(pResult.extension);
					$.each(pResult.apApplications, function (key, val) {
						extensionView.push(val);
					});
					extPrgPhotos(pResult.apOnlineExtPrgPhotos);
					apExtensionInfo(pResult.apExtensionInfo);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_extension_error"])
				}
			}, common.GetAupairID());
		},

		GetAdmin = function () {

			greyedBackground.show();
			var AupairID = common.GetAupairID();
			ds.aupairView.GetAdmin({
				success: function (pResult) {
					greyedBackground.hide();
					adminView(pResult);
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["viewer_load_evaluation_error"])
				}
			}, AupairID);

		},

		TranslateBoolToText = function (data, notes) {
			if (data == true)
				return 'Yes' + (notes != undefined && notes != '' ? '. ' : '');
			else
				return 'No' + (notes != undefined && notes != '' ? '. ' : '');
		},

		capitaliseFirstLetter = function (string) {
			if (string != null)
				return string.charAt(0).toUpperCase() + string.slice(1);
			else
				return string;
		},

		getAgeGroups = function (pAgeGroupCode) {
			var ageGroupText = '';
			$(pAgeGroupCode.split('')).each(function (index, character) {
				if (character == 1)
					ageGroupText = ageGroupText + ageGroups[index] + ', '
			});

			return ageGroupText.slice(0, -2);
		},

		getTimeOfDaycare = function (pDaycareCode) {
			var timeOfDaycareText = '';
			$(pDaycareCode.split('')).each(function (index, character) {
				if (character == 1)
					timeOfDaycareText = timeOfDaycareText + timesOfDaycare[index] + ', '
			});
			return timeOfDaycareText.slice(0, -2);
		},

		getMoreChildExpAgeGroups = function (pCode) {
			var ageGroupText = '';
			$(pCode.split('')).each(function (index, character) {
				if (character == 1)
					ageGroupText = ageGroupText + moreChildExpAgeGroups[index] + ', '
			});

			return ageGroupText.slice(0, -2);
		},

		 GetMyPreferences = function () {
			 greyedBackground.show();
			 var AupairID = common.GetAupairID();
			 ds.aupairView.GetAdmin({
				 success: function (pResult) {
					 greyedBackground.hide();
					 myPreferencesView(pResult);
				 },
				 error: function () {
					 greyedBackground.hide();
					 common.ErrorNotify(msgs["viewer_load_contact_error"])
				 }
			 }, AupairID);
		 },

		GetDocument = function (pDocumentID, pName) {
			window.open('/GetDocument.ashx?Format=PDF&Name=' + pName + '&ID=' + pDocumentID);
		},

		GetExtnDocument = function (pData) {
			window.open('/GetDocument.ashx?DocType=extension&Format=' + pData.AppType.toUpperCase() + '&appURL=' + pData.AppURL);
		},

		ViewExtnPhoto = function (pData) {
			window.open('/GetDocument.ashx?DocType=apOnlineExtPrgPhotos&Format=IMAGE&appURL=' + pData.PhotoPath);
		},

		printInit = function (val) {
			isPrint(true);
			GetContactInformation(true);
			GetMyFamily();
			GetMyPreferences();
			GetMyLifestyle();
			GetMyHealth();
			GetChildcareExperience();
			GetReferences();
			GetWorkExperience();
			GetEvaluation();
			GetDrivingSwimming();
			GetInterests();
			GetEducation();
			GetLetter();
			GetExtension();
			if (personType() == 'STAFF' || personType() == 'LCC')
				GetAdmin();
		},

		OpenPrintWindow = function () {
			var AupairID = common.GetAupairID();
			var pt = common.GetQueryStringValue('pt');
			//window.open('/PrintAupairApplication?A=' + AupairID, '_blank', 'print', 'width=800,height=600')
			window.open('/PrintAupairApplication?A=' + AupairID + '&pt=' + pt, 'printwindow', 'width=1000, height=800, scrollbars=yes')
		},

		Print = function () {
			window.print();
		},

		ShowSection = function (section, sectionID) {
			if (section == 'references') {
				$("#aReferences").click();
				scrollPage = true;
				scrollToID = sectionID;
			}
			else if (section == 'childcare-exp') {
				$("#aChildcareExp").click();
				scrollPage = true;
				scrollToID = sectionID;
			}
			else if (section == 'health') {
				$("#aHealth").click();
				scrollPage = true;
				scrollToID = sectionID;
			}
		},

	TabNavigation = function (tab) {

		if (tab == 'contact') {
			GetContactInformation(false);
		}
		else if (tab == 'family') {
			GetMyFamily();
		}
		else if (tab == 'lifestyle') {
			GetMyLifestyle();
		}
		else if (tab == 'health') {
			GetMyHealth();
		}
		else if (tab == 'childcare-exp') {
			GetChildcareExperience();
		}
		else if (tab == 'references') {
			GetReferences();
		}
		else if (tab == 'work-exp') {
			GetWorkExperience();
		}
		else if (tab == 'evaluations') {
			GetEvaluation();
		}
		else if (tab == 'driving-swimming') {
			GetDrivingSwimming();
		}
		else if (tab == 'interests') {
			GetInterests();
		}
		else if (tab == 'education') {
			GetEducation();
		}
		else if (tab == "extension") {
			GetExtension();
		}
		else if (tab == "admin") {
			GetAdmin();
		}
		else if (tab == "letter") {
			GetLetter();
		}
		else if (tab == "mypreferences") {
			GetMyPreferences();
		}
	},

	CaptionOverflow = function () {

		var nbLinesToDisplay = 2;
		$('.flex-caption').each(function () {

			var closedHeight = 0;

			var divheight = $(this).height();
			var lineheight = $(this).css('line-height').replace("px", "");
			var nbLines = Math.round(divheight / parseInt(lineheight));

			if (nbLines > nbLinesToDisplay) {

				var closedHeight = parseInt(lineheight) * (nbLinesToDisplay + 1);

				$(this).css('height', closedHeight);

				$(this).addClass('caption-overflow');
			}
		});
	},

	InvokeSlider = function () {

		$(CONTAINER + ' .gs-list > li:first-child').attr({ 'data-colspan': 2, 'data-rowspan': 2 });

		//initialize grid slider
		slider = $(CONTAINER).gridSlider({
			responsive: true,
			numCols: 4,
			slideWidth: 5,
			slideHeight: 4,
			slideMargin: 5,
			captionEffect: 'slide',
			keyboard: true,
			control: 'none',
			pageInfo: false,
			playButton: false,
			timer: false,
		});

		function doneResizing() {
			var vid = $('#slider1 .gs-bin-item .hasVideo');
			vid.find('.gs-bg-img').css({ 'line-height': vid.height() + 'px' });
		}

		$(window).on('resize', function () {
			doneResizing();
		}).resize();


		$(document).on('tap', function () {
			$('.gs-bin-item').magnificPopup({
				delegate: 'li:not(.hasVideo)',
				type: 'image',
				image: {
					titleSrc: function (item) {
						return item.el.find('.gs-caption').text();
					}
				},
				callbacks: {
					imageLoadComplete: function () {
						$(this.content).show();
					},
					beforeChange: function (item) {
						$(this.content).hide();
					},
				},
				gallery: {
					enabled: true, // set to true to enable gallery
					navigateByImgClick: true,
					arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>', // markup of an arrow button
					tPrev: 'Previous (Left arrow key)', // title for left button
					tNext: 'Next (Right arrow key)', // title for right button
					tCounter: '%curr% of %total%' // markup of counter
				}
			});
		});

	},

	WatchVideo = function () {
		common.WatchVideo(aupairInformation());
	},

	GetVideoThumbUrl = function () {
		return '/GetImage.ashx?p=' + aupairInformation().VideoThumbUrl + '&w=245&h=245';
	},

	GetExtnAppName = function (fileName) {
		if (fileName.indexOf('HFReference') > -1) {
			return "Host family reference";
		}
		else if (fileName.indexOf('Addendum') > -1) {
			return "Extension application";
		}
		else if (fileName.indexOf('LCCReference') > -1) {
			return "LCC reference";
		}
		else
			return fileName;
	},

	ReserveAupair = function () {
		greyedBackground.show();
		var apID = common.GetAupairID();
		ds.reserveAupair.ReserveAupair({
			success: function (pResult) {
				greyedBackground.hide();
				if (pResult == "Successful") {
					//init(false);
					common.SuccessNotify(msgs["reserve_ap_success"]);
					window.location.href = viewModels.reservedPageURL;
				}
				else if (pResult != "") {
					if (pResult == 'restrict-48-hour-hold') {
						selectedAupairForExtendedHold(apID);
						if (primaryMatches().length > 0) {
							if ((primaryMatches()[0].Status != "PM" && primaryMatches()[0].Status != "PME") ||
								primaryMatches()[0].Is48HourHoldRestrictionApplies == true) {
								$('.make-pm-48hr-restrict').find('.releaseExtnHold').show();
							}
						}

						makePMFor48HrRestrict();
					}
					else if (pResult == 'BlockedReserve') {
						$('#blockreservefavholdaupairspan').text(msgs["blockrestrictmessage"].replace("<<PlacementManager>>", hfpmname().FullName));
						$(this).scrollTop(0);
					}
					else
						common.ErrorNotify(pResult);
				}
				else {
					common.ErrorNotify(msgs["reserve_ap_error"]);
				}
			},
			error: function () {
				greyedBackground.hide();
				common.ErrorNotify(msgs["reserve_ap_error"]);
			}
		},
		{
			AuPairId: apID
		});
	},

	GetLetter = function () {
		greyedBackground.show();
		var AupairID = common.GetAupairID();
		ds.aupairView.GetLetter({
			success: function (pResult) {
				greyedBackground.hide();
				apLetter(pResult.letter);
			},
			error: function () {
				greyedBackground.hide();
				common.ErrorNotify(msgs["viewer_load_letter_error"])
			}
		}, AupairID);
	},

	ReleaseAuPair = function () {
		$.magnificPopup.open({
			type: 'inline',
			closeOnContentClick: false,
			closeOnBgClick: true,
			showCloseBtn: false,
			enableEscapeKey: false,
			items: {
				src: '#releaseAuPair'
			}
		});
	},

	ConfirmReleaseAuPair = function (data, event) {
		//Remove the previous validation error messages
		$(event.target).parents('div.releaseAuPair').find('.line-break').remove()
		$(event.target).parents('div.releaseAuPair').find('.release-reason').parent().find('span[class="error"]').remove();

		var selectedCM = '';
		var isError = false;
		if (comparisonMatches().length > 1 && IsPrimaryMatch()) {
			$(event.target).parents().find('p.select-a-cm').find('.cmList').parent().find('span[class="error"]').remove();

			selectedCM = $('input:radio[name="selectCM"]:checked').val();
			if (selectedCM == undefined || selectedCM == '') {
				$(event.target).parents().find('p.select-a-cm').after($('<span class="error">').text("Please choose any one of the following before proceeding"));
				isError = true;
			}
		}

		var aupairNo = this.vmapv.AupairInformation().AuPairNo;
		var selectedValues = $('input:checkbox[name="' + 'release_' + aupairNo + '"]:checked').map(function () { return this.value; }).get().join(' ');
		var reason = $(':input[name="' + 'release_reason_' + aupairNo + '"]').val();
		if (selectedValues == '') {
			$(event.target).parents('div.releaseAuPair').find('.release-reason').after($('<span class="error">').text("Please choose at least one reason of why you would like this match released from your account."));
		}
		else if ($('input:checkbox[name="' + 'release_' + aupairNo + '"][value="Other"]').is(':checked') && reason == "") {
			$('input:checkbox[name="' + 'release_' + aupairNo + '"][value="Other"]').siblings('label').after($('<br class="line-break" />'));
			$(event.target).parents('div.releaseAuPair').find('.line-break').after($('<span class="error">').text("Please elaborate on why you would like to release this au pair."))
			$(':input[name="' + 'release_reason_' + aupairNo + '"]').focus();
		}
		else {
			if (!isError) {
				if (this.vmapv.IsPrimaryMatch()) {
					if (selectedCM == '' && comparisonMatches()[0] != undefined) {
						selectedCM = comparisonMatches()[0].AupairKey;
					}
					ReleasePMAupair(selectedValues, reason, selectedCM);
				}
				else
					ReleaseCMAupair(selectedValues, reason);
			}
		}
	},

	ReleasePMAupair = function (selectedValues, reason, pSelectedCM) {
		greyedBackground.show();
		ds.reserveAupair.ReleasePMAupair({
			success: function (pResult) {
				greyedBackground.hide();
				if (pResult == "Successful") {
					CanReserveAndFavoriteAupair();
					$.magnificPopup.close();
					common.SuccessNotify(msgs["reserve_relese_pm_success"]);
				}
				else {
					common.ErrorNotify(pResult);
				}
			},
			error: function () {
				greyedBackground.hide();
				common.ErrorNotify(msgs["reserve_release_pm_error"]);
			}
		},
		{
			pAupairID: common.GetAupairID(this),
			pReason: selectedValues + ' ' + reason,
			pSelectedCM: pSelectedCM
		});
	},

	ReleaseCMAupair = function (selectedValues, reason) {
		greyedBackground.show();
		ds.reserveAupair.ReleaseAupair({
			success: function (pResult) {
				greyedBackground.hide();
				if (pResult == "Successful") {
					CanReserveAndFavoriteAupair();
					$.magnificPopup.close();
					common.SuccessNotify(msgs["reserve_release_cm_success"]);
				}
				else {
					common.ErrorNotify(pResult);
				}
			},
			error: function () {
				greyedBackground.hide();
				common.ErrorNotify(msgs["reserve_release_cm_error"]);
			}
		},
		{
			pAupairID: common.GetAupairID(),
			pReason: selectedValues + ' ' + reason
		});
	},

	CancelAuPairRelease = function (data, event) {
		//Remove the validation error messages
		$(event.target).parents('div.releaseAuPair').find('.line-break').remove()
		$(event.target).parents('div.releaseAuPair').find('.release-reason').parent().find('span[class="error"]').remove();
		$('input:checkbox[name="' + 'release_' + this.vmapv.AupairInformation().AuPairNo + '"]').attr('checked', false);
		$(':input[name="' + 'release_reason_' + this.vmapv.AupairInformation().AuPairNo + '"]').val('');
		$('input:radio[name="selectCM"]').attr('checked', false);
		$.magnificPopup.close();
	},

	PostFeedback = function (pAupairID, obj) {
		$(event.target).parents('li.thumb').find('.formbox-container').find('.feedback-title').parent().find('span[class="error"]').remove();

		var control = $('input:radio[name="' + 'st3_' + pAupairID + '"]:checked').next()[0];
		var message = '';
		if (control == undefined) {
			$(event.target).parents('li.thumb').find('.formbox-container').find('.feedback-title').after($('<span class="error">').text("Please select an option below"));
		}
		else {
			message = control.innerHTML;

			var reason = $(':input[name="' + 'st3_reason' + pAupairID + '"]').val();
			greyedBackground.show();
			ds.reserveAupair.PostFeedback({
				success: function (pResult) {
					greyedBackground.hide();
					if (pResult == "Successful") {
						$('.close-box').trigger('click');
						common.SuccessNotify(msgs["reserve_feedback_success"]);
					}
					else {
						common.ErrorNotify(pResult);
					}
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["reserve_feedback_error"]);
				}
			},
			{
				pAupairID: common.GetAupairID(this),
				pMessage: message,
				pReason: reason
			});
		}
	},

	LCCReleaseAupair = function () {

		var reason = $('#txtLCC_ReleaseReason').val();
		greyedBackground.show();
		ds.aupair.LCCReleaseAupair({
			success: function (pResult) {

				if (pResult == "Successful") {
					favAp.GetStaffDuties();
					$.magnificPopup.close();
					greyedBackground.hide();
					common.SuccessNotify("Aupair released successfully.");
				}
				else {
					greyedBackground.hide();
					common.ErrorNotify(pResult);
				}

			},
			error: function () {
				greyedBackground.hide();
				common.ErrorNotify("Error while releasing an aupair");
			}
		},
		{
			AuPairId: common.GetAupairID(),
			Reason: reason
		});
	},

	OpenRecommendAupair = function () {

		$.magnificPopup.open({
			type: 'inline',
			closeOnContentClick: false,
			closeOnBgClick: true,
			showCloseBtn: true,
			enableEscapeKey: true,
			items: {
				src: '#divRecommendAupair'
			}
		});

	},

	RecommendAupair = function () {

		var comment = $('#txtRecommendAupair').val();
		greyedBackground.show();
		ds.aupair.RecommendAupair({
			success: function (pResult) {

				if (pResult == "Successful") {
					favAp.GetStaffDuties();
					$.magnificPopup.close();
					//$('.recommend-aupair').hide();
					greyedBackground.hide();
					common.SuccessNotify("Aupair recommended successfully.");
				}
				else {
					greyedBackground.hide();
					if (pResult == "Only active (ACT) host families can have au pairs reserved for them.")
						common.ErrorNotify("You can only recommend au pairs to active (ACT) host families.");
					else
						common.ErrorNotify(pResult);
				}

			},
			error: function () {
				greyedBackground.hide();
				common.ErrorNotify("Error while recommending an aupair");
			}
		},
		{
			pAupairId: common.GetAupairID(),
			pComment: comment
		});
	},

	RemoveRecommendedAupair = function () {
		ds.aupair.RemoveRecommendedAupair({
			success: function (pResult) {
				if (pResult == "Success") {
					favAp.GetStaffDuties();
					//$('.remove-from-recommend-aupair').hide();
					$.magnificPopup.close();
					common.SuccessNotify(msgs["recommended_ap_remove_success"]);
				}
				else {
					common.ErrorNotify(pResult);
				}
			},
			error: function () {
				common.ErrorNotify(msgs["recommended_ap_remove_error"]);
			}
		},
		{
			pAupairID: common.GetAupairID(),
		})
	},

	getMoreChildExpText = function (CanGetMoreChildExp, MoreChildExpBitmask) {
		var textValue = '';
		if (CanGetMoreChildExp == 'Yes') {
			textValue = 'Yes, I can. The children would be ' + getMoreChildExpAgeGroups(MoreChildExpBitmask) + '.';
		}
		else if (CanGetMoreChildExp == 'No') {
			textValue = 'No, I cannot.';
		}
		else if (CanGetMoreChildExp == 'Maybe') {
			textValue = 'Maybe, I am not sure. The children might be ' + getMoreChildExpAgeGroups(MoreChildExpBitmask) + '.';
		}

		return textValue;
	},

	UpdateFavoriteComment = function (data, event) {
		var comments = $(event.target).parents('.favorites-comment-box').find('.favoriteComment').val();
		if (comments != '') {
			favAp.SaveFavoriteComment(common.GetAupairID(), comments);
		}
		else {
			$(".favorites-comment-box").hide();
		}
	},

	GetComparisonMatches = function () {
		comparisonMatches.removeAll();
		ds.reserveAupair.GetComparisonMatches({
			success: function (pResult) {
				$.each(pResult, function (key, val) {
					comparisonMatches.push(val);
				});
			},
			error: function () {
				common.ErrorNotify(msgs["reserve_load_cm_error"])
			}
		});
	},

	IsPrimaryMatch = function () {
		if (aupairInformation().Status == "PM"
			|| aupairInformation().Status == "PME"
			|| aupairInformation().Status == "PMX"
			|| aupairInformation().Status == "PMXE")
			return true;
		else
			return false;
	},

	showCountryCultureInfo = function () {
		var countryName = $.trim(aupairInformation().CountryName).toLowerCase();

		ds.aupair.GetCountryCultureInfo({
			success: function (val) {
				apCountryCultureInfo(val);
				if (val != '') {
					$('.globe-popup').find('h2').text(countryName);

					$.magnificPopup.open({
						items: {
							type: 'inline',
							src: '#country-culture-info'
						},
						closeOnContentClick: false,
						closeOnBgClick: false,
						showCloseBtn: true,
						closeBtnInside: true
					});
				}
			},
			error: function (response) {
				greyedBackground.hide();
				common.ErrorNotify("Error while loading culture info");
			}
		}, countryName);
	},

	getAPFirstName = function () {
		if (aupairInformation().FirstName != undefined && aupairInformation().FirstName != null && aupairInformation().FirstName != "")
			return aupairInformation().FirstName.split(" ")[0];
		return "";
	},

	IsAPReserved = function () {
		if (IsPrimaryMatch())
			return true;
		else {
			if (aupairInformation().Status.match("PP"))
				return true;
			else
				return false;
		}
	},

	getPrimaryMatchesofFamily = function () {
		primaryMatches.removeAll();
		ds.reserveAupair.GetPrimaryMatches({
			success: function (pResult) {
				$.each(pResult, function (key, val) {
					primaryMatches.push(val);
				});
			},
			error: function () {
			}
		});
	},

	makePMFor48HrRestrict = function () {
		$.magnificPopup.open({
			type: 'inline',
			closeOnContentClick: false,
			closeOnBgClick: true,
			showCloseBtn: false,
			enableEscapeKey: false,
			items: {
				src: '.make-pm-48hr-restrict'
			}
		});
	},

	ReleaseCurrentExtnHold = function (data, event) {
		$(event.target).parents('.make-pm-48hr-restrict').find('.releaseExtnHold').show();
		$(event.target).parents('.make-pm-48hr-restrict').find('span[class="error"]').remove();
		return true;
	},

	AddCurrentExtnHoldAsPPM = function (data, event) {
		$(event.target).parents('.make-pm-48hr-restrict').find('.releaseExtnHold').hide();
		$(event.target).parents('.make-pm-48hr-restrict').find('input:checkbox[class="extnHoldRelease"]').prop('checked', false);
		$(event.target).parents('.make-pm-48hr-restrict').find(':input[name="extnHoldReleaseText"]').val('');
		$(event.target).parents('.make-pm-48hr-restrict').find('span[class="error"]').remove();
		return true;
	},

	SetAsExtendedHold = function (data, event) {
		var validationError = '';
		var selOption = $(event.target).parents('.make-pm-48hr-restrict').find('input[name=extendedHoldOperation]:checked').map(function () { return this.value; }).get().join(' ');
		$(event.target).parents('.make-pm-48hr-restrict').find('span[class="error"]').remove();

		if (primaryMatches().length > 0) {
			if ((primaryMatches()[0].Status != "PM" && primaryMatches()[0].Status != "PME") ||
				primaryMatches()[0].Is48HourHoldRestrictionApplies == true) {
				selOption = 'Release';
			}
		}

		if (selOption == '') {
			$(event.target).parents('.make-pm-48hr-restrict').find('.currPMActionTitle').
				after($('<span class="error">').text("Please choose at least one option of what would you like to do with the current extended hold."));
		}
		else {
			if (selOption == 'Release') {
				//Remove the previous validation error messages
				$(event.target).parents('.make-pm-48hr-restrict').find('.line-break').remove();
				$(event.target).parents('.make-pm-48hr-restrict').find('.primaryRelease-reason').parent().find('span[class="error"]').remove();

				var selectedValues = $('input:checkbox[name="extnHoldRelease"]:checked').map(function () { return this.value; }).get().join(' ');
				var reason = $(':input[name="extnHoldReleaseText"]').val();
				if (selectedValues == '') {
					$(event.target).parents('.make-pm-48hr-restrict').find('.primaryRelease-reason').after($('<span class="error">').text("Please choose at least one reason of why you would like your current extended hold released from your account."));
					validationError = 'yes';
					return false;
				}
				else if (selectedValues == 'Other' && reason == "") {
					$('input:checkbox[name="extnHoldRelease"][value="Other"]').siblings('label').after($('<br class="line-break" />'));
					$(event.target).parents('.make-pm-48hr-restrict').find('.line-break').after($('<span class="error">').text("Please elaborate on why you would like to release your current extended hold."))
					$(':input[name="extnHoldReleaseText"]').focus();
					validationError = 'yes';
					return false;
				}
				else {
					validationError = '';
				}
			}

			if (validationError == '') {
				greyedBackground.show();
				ds.reserveAupair.PrimaryMatch({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Successful") {
							$('.close-box').trigger('click');
							common.SuccessNotify(msgs["reserve_pm_success"]);
							window.location.href = viewModels.reservedPageURL;
						}
						else {
							common.ErrorNotify(pResult);
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["reserve_pm_error"]);
					}
				},
				{
					AuPairId: selectedAupairForExtendedHold(),
                    Reason: selectedValues + ' ' + reason,
                    CurrPMAction: selOption
				});
			}
		}
	},

	DonotSetAsExtendedHold = function (data, event) {
		$(event.target).parents('.make-pm-48hr-restrict').find('.releaseExtnHold').hide();
		$(event.target).parents('.make-pm-48hr-restrict').find('span[class="error"]').remove();
		$(event.target).parents('.make-pm-48hr-restrict').find('input:checkbox[name="extnHoldRelease"]').prop('checked', false);
		$(event.target).parents('.make-pm-48hr-restrict').find(':input[name="extnHoldReleaseText"]').val('');
		$(event.target).parents('.make-pm-48hr-restrict').find('input[name=extendedHoldOperation]').prop('checked', false);
		return true;
	};

		return {
			Init: init,
			MakeAupairFavorite: MakeAupairFavorite,
			RemoveAPfromFav: favAp.RemoveAPfromFav,
			ReserveAupair: ReserveAupair,
			TabNavigation: TabNavigation,
			AupairInformation: aupairInformation,
			HeadingNotes: headingNotes,
			AupairPhotos: aupairPhotos,
			ContactInformationView: contactInformationView,
			MyPreferencesView: myPreferencesView,
			MyFamilyView: myFamilyView,
			MyLifestyleView: myLifestyleView,
			MyHealthView: myHealthView,
			ChildcareExperienceView: childcareExperienceView,
			ReferencesView: referencesView,
			WorkExperienceView: workExperienceView,
			EvaluationView: evaluationView,
			AdminView: adminView,
			DrivingSwimmingView: drivingSwimmingView,
			InterestsView: interestsView,
			EducationView: educationView,
			TranslateBoolToText: TranslateBoolToText,
			CanReserveAndFavoriteAupair: CanReserveAndFavoriteAupair,
			CanReserve: canReserve,
			CapitaliseFirstLetter: capitaliseFirstLetter,
			GetAgeGroups: getAgeGroups,
			GetTimeOfDaycare: getTimeOfDaycare,
			GetDocument: GetDocument,
			PrintInit: printInit,
			OpenPrintWindow: OpenPrintWindow,
			IsPrint: isPrint,
			Print: Print,
			ShowSection: ShowSection,
			APStatus: apStatus,
			CanFavorite: canFavorite,
			GetReserveButtonStyle: common.GetReserveButtonStyle,
			GetLCCReserveButtonTooltip: common.GetLCCReserveButtonTooltip,
			GetLCCReserveButtonStyle: common.GetLCCReserveButtonStyle,
			CanLCCReserveAupair: common.CanLCCReserveAupair,
			GetReserveButtonTooltip: common.GetReserveButtonTooltip,
			ExtensionView: extensionView,
			ExtPrgPhotos: extPrgPhotos,
			GetExtnDocument: GetExtnDocument,
			ExtensionTabVisible: extensionTabVisible,
			WatchVideo: WatchVideo,
			GetExtnAppName: GetExtnAppName,
			ViewExtnPhoto: ViewExtnPhoto,
			ShowInformation: showInformation,
			GetLockedClass: GetLockedClass,
			APLetter: apLetter,
			GetMyPreferences: GetMyPreferences,
			ReleaseAuPair: ReleaseAuPair,
			ConfirmReleaseAuPair: ConfirmReleaseAuPair,
			CancelAuPairRelease: CancelAuPairRelease,
			OpenRecommendAupair: OpenRecommendAupair,
			RecommendAupair: RecommendAupair,
			GetMoreChildExpAgeGroups: getMoreChildExpAgeGroups,
			GetMoreChildExpText: getMoreChildExpText,
			RemoveRecommendedAupair: RemoveRecommendedAupair,
			ComparisonMatches: comparisonMatches,
			LCCReleaseAupair: LCCReleaseAupair,
			GetContactInformation: GetContactInformation,
			ApProfileAndEEView: apProfileAndEEView,
			IsPrimaryMatch: IsPrimaryMatch,
			IsCurrentAP: isCurrentAP,
			UpdateFavoriteComment: UpdateFavoriteComment,
			PostFeedback: PostFeedback,
			ShowCountryCultureInfo: showCountryCultureInfo,
			APCountryCultureInfo: apCountryCultureInfo,
			GetAPFirstName: getAPFirstName,
			ShowExtentionInfo: showExtentionInfo,
			GetVideoThumbUrl: GetVideoThumbUrl,
			GetReserveButtonText: common.GetReserveButtonText,
			PrimaryMatches: primaryMatches,
			SetAsExtendedHold: SetAsExtendedHold,
			DonotSetAsExtendedHold: DonotSetAsExtendedHold,
			AddCurrentExtnHoldAsPPM: AddCurrentExtnHoldAsPPM,
			ReleaseCurrentExtnHold: ReleaseCurrentExtnHold,
			APExtensionInfo: apExtensionInfo,
			SetPersonType: SetPersonType,
			PersonType: personType,
			AddAsFavAP: favAp.AddAsFavAP,
			RemoveFavAP: favAp.RemoveFavAP,
			RemoveFromFavorite: favAp.RemoveFromFavorite,
			HasValidHFKey: HasValidHFKey,
			Appcode: appcode,
			SetAppCode: SetAppCode,			
		}
	});